<?php

declare(strict_types=1);

namespace app\controller\trade;

use app\BaseController;
use app\service\cart\CartService;
use app\service\cart\StockVerificationService;
use app\service\factory\ResponseFactory;
use app\validate\cart\CartValidate;
use think\Response;
use Throwable;

class Cart extends BaseController
{
    public function index(CartService $cartService): Response
    {
        try {
            $buyerId = (int) ($this->request->user_id ?? 0);
            if ($buyerId <= 0) {
                return json(ResponseFactory::error('未登录或缺少用户信息', 401));
            }

            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;

            $filters = $this->request->only(['status', 'seller_org_id'], 'get');
            $paginator = $cartService->paginate($buyerId, $filters, $page, $pageSize);
            $list = $cartService->formatCollection($paginator->items());

            return json(ResponseFactory::paginated(
                $list,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function save(CartService $cartService): Response
    {
        try {
            $buyerId = (int) ($this->request->user_id ?? 0);
            if ($buyerId <= 0) {
                return json(ResponseFactory::error('未登录或缺少用户信息', 401));
            }

            $payload = $this->request->only([
                'product_id',
                'prod_id',
                'sku_id',
                'qty',
                'remark',
                'source_type',
                'channel',
            ], 'post');
            $this->validate($payload, CartValidate::class . '.create');
            $payload['buyer_id'] = $buyerId;

            $cart = $cartService->add($payload);

            return json(ResponseFactory::success($cartService->format($cart), '已加入购物车'));
        } catch (Throwable $e) {
            $code = $e->getCode() ?: 500;
            if ($code >= 600 || $code < 100) {
                $code = 500;
            }
            return json(ResponseFactory::error($e->getMessage(), $code));
        }
    }

    public function update(int $id, CartService $cartService): Response
    {
        try {
            $buyerId = (int) ($this->request->user_id ?? 0);
            if ($buyerId <= 0) {
                return json(ResponseFactory::error('未登录或缺少用户信息', 401));
            }

            $payload = $this->request->only([
                'qty',
                'remark',
                'status',
            ], 'put');
            $this->validate($payload, CartValidate::class . '.update');

            $cart = $cartService->update($id, $buyerId, $payload);

            return json(ResponseFactory::success($cartService->format($cart), '购物车已更新'));
        } catch (Throwable $e) {
            $code = $e->getCode() ?: 500;
            if ($code >= 600 || $code < 100) {
                $code = 500;
            }
            return json(ResponseFactory::error($e->getMessage(), $code));
        }
    }

    public function delete(int $id, CartService $cartService): Response
    {
        try {
            $buyerId = (int) ($this->request->user_id ?? 0);
            if ($buyerId <= 0) {
                return json(ResponseFactory::error('未登录或缺少用户信息', 401));
            }

            $cartService->remove($id, $buyerId);

            return json(ResponseFactory::success(true, '购物车已删除'));
        } catch (Throwable $e) {
            $code = $e->getCode() ?: 500;
            if ($code >= 600 || $code < 100) {
                $code = 500;
            }
            return json(ResponseFactory::error($e->getMessage(), $code));
        }
    }

    public function spotCheck(int $id, CartService $cartService, StockVerificationService $stockService): Response
    {
        try {
            $buyerId = (int) ($this->request->user_id ?? 0);
            if ($buyerId <= 0) {
                return json(ResponseFactory::error('未登录或缺少用户信息', 401));
            }

            $payload = $this->request->only([
                'buyer_qty',
                'buyer_remark',
                'buyer_media',
            ], 'post');
            $record = $stockService->createFromCart($id, $buyerId, $payload ?? []);

            return json(ResponseFactory::success($record->toArray(), '已发起现货核实'));
        } catch (Throwable $e) {
            $code = $e->getCode() ?: 500;
            if ($code >= 600 || $code < 100) {
                $code = 500;
            }
            return json(ResponseFactory::error($e->getMessage(), $code));
        }
    }
}
